/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.org.mtgatherer.priceloaders;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author Evgen
 */
public class StarCityPriceLoader implements IPriceLoader {

   private final String FOIL_ATTRIBUTE = "Foil";
   private final Pattern SET_FOIL_PATTERN = Pattern.compile("(.*)\\((.*)\\)");

   @Override
   public List<CardPrice> getCardPrice(String cardName) throws IOException, URISyntaxException
   {
      List<CardPrice> prices = new LinkedList<CardPrice>();

      Element priceTable = exatractPriceTable(cardName);

      if (priceTable != null)
      {
         System.out.println("GOTCHA");
      }

      Iterator<Element> elementIterator = priceTable.getElementsByTag("tr").iterator();

      int i = 0;

      String setAndFoil = null;

      Element currentElement = null;

      while (elementIterator.hasNext())
      {
         currentElement = elementIterator.next();

         if (currentElement.getElementsByTag("hr").isEmpty())
         {
            if (currentElement.getElementsByTag("a").isEmpty())
            {
               throw new IOException("HTML <hr> element in price table not found. Something wrong with HTML markup.");
            }
            continue;
         }

         CardPrice cardPrice = new CardPrice();

         currentElement = elementIterator.next();

         Element cardNameElement = currentElement.getElementsByTag("span").first();

         if (cardNameElement.ownText().equals(cardName))
         {
            setAndFoil = currentElement.getElementsByTag("a").first().ownText();

            Matcher matcher = SET_FOIL_PATTERN.matcher(setAndFoil);

            if (matcher.find())
            {
               cardPrice.setCardSet(matcher.group(1));

               if (matcher.group(2).equals(FOIL_ATTRIBUTE))
               {
                  cardPrice.setFoil(true);
               }
            }
            else
            {
               cardPrice.setCardSet(setAndFoil);
            }
         }

         currentElement = elementIterator.next();

         Element conditionElement = currentElement.getElementsByTag("a").first();

         cardPrice.setCondition(conditionElement.ownText());

         Element priceElement = currentElement.getElementsByTag("b").first();

         cardPrice.setPrice(Float.parseFloat(priceElement.ownText().substring(1)));

         cardPrice.setCurrency("USD");



         System.out.println(cardPrice);


      }

      return null;
   }

   private Element exatractPriceTable(String cardName) throws IOException, URISyntaxException
   {
      Element priceTable = null;

      final URI uri = new URI("http", "sales.starcitygames.com", "/cardsearch.php",
              "singlesearch=" + cardName, null);

      final String actualUrl = uri.toURL().toString();

      final Document cardPage = Jsoup.connect(actualUrl).get();

      final Elements elements = cardPage.getElementsByTag("table");

      for (Element element : elements)
      {
         if (element.hasAttr("width") && element.attr("width").equals("80%"))
         {
            if (priceTable == null)
            {
               priceTable = element;
            }
            else
            {
               throw new IOException("Tables with price more than one.");
            }
         }
      }

      return priceTable;
   }
}
